/*
 * @Descripttion: 
 * @version: 
 * @Author: LLP
 * @Date: 2019-12-15 17:46:57
 * @LastEditors: LLP
 * @LastEditTime: 2019-12-22 09:48:06
 */
import router from './router'
import store from './store'
import { Message } from 'element-ui'
import { getToken } from '@/filter/auth' // get token from cookie

const whiteList = ['/login'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {

  // determine whether the user has logged in
  const hasToken = getToken()
  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
    } else {
      const someinfo = store.getters.someinfo
      if (someinfo) {
        next()
      } else {
        try {
          // get user info
          await store.dispatch('setsomeinfo')
          await store.dispatch('orLogin', true)
          await store.dispatch('getNickname')
          next()
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch('resetToken')
          await store.dispatch('orLogin', false)
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
        }
      }
    }
  } else {
    /* has no token*/

    if (whiteList.indexOf(to.path) !== -1) {      // in the free login whitelist, go directly
      next()
    } else {
      console.log(to.path, 'redirect')
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
    }
  }
})

router.afterEach(() => {
  // finish progress bar
})